
/*
*Pool Public Licence version 0.1 or later
*Released on 20th April 2008.
*Any voilations can be repoted at paritosh@wikiocean.net
*What is treated as voilations can be found at www.wikiocean.net/ppl1-voilations* 
******************************************************************************
* The contents of this file are subject Affero GPL v3 and later with additional conditions.
* The additional conditions are to be considered as part of the Affero GPL v3 and later.
* The additional conditions will supersede the Affero GPLv3 and later in case of conflict.
* ("License"); You may not use this file except in compliance with the License
* You may obtain a copy of the License at http://www.gnu.org/licenses/agpl.html
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* The Initial Developer of the Original Code is Paritosh Pungaliya.
* created by Paritosh Pungaliya are Copyright (C) Paritosh Pungaliya; All Rights Reserved.
* Contributions are Copyright (C) 2001-2008 Paritosh Pungaliya.

* Objective of the additional terms (license) 
* 1) Is to extend the software freedom to freedom to work.
* 2) To ensure that knowledge is free from monopoly of agencie(s).
* 3) To avoid a situation where big corporates or investors can buy out free software groups and companies and then start milking the communities built around it.
* (this trend can be seen how the openness changes in companies that get Venture Capital funding.)
* (if you agree to this logic I invite you to our group to work together)

* Additional conditions
*  0) Source code will also include
* 	a) data dictionaries, data ontologies which are used to alter the behavior of code or to control           the features of application.
* 	b) Any code generated or derived automatically or manually from this code or logic
*  1) The revenue generated by deploying, implementing , selling services and other activities
*  	 based on this source code should be shared 100%, between the people working on it.
*  2) Capital invested should be given only fixed rate of return or linked to revenue/surplus growth for limited time.
*  3) People working on the project should always have an option to replace the capital provider in full or part with lower cost capital.
*  4) Their should not be any ownership which can be sold as a claim on future profit to be generated from the work of people working on the code.
*  5) Brand thus generated should belong to the group.
*  6) For old and new members revenue sharing should be equal for same work equivalent.
*  7) The share of revenue should be decided by bidding for work before allocation of work within the group.
*  8) Before bidding various method of measuring the work should be clearly defined and published in public domain. Any change in process should also be publised in public domain imediately.
*  9) All data related to to revenue sharing should be published as and when generated in public domain.
*  10) For group of people having size more than 10 people will have to make it open online for others to participate in bids. 
*  11) All people involved in related and sub project will be treated as a group.
*  12) Once this license is being used for a certain code then all and any other software services being provided by the group should complusorilly come under 100% revenue sharing.
*  13) Cross subsidization should not happen under this revenue share, no additional benefit should be drawn from the people, by the employing agency.
*  14) Any position or knowledge or legal structure created relating to people working on code, which adversely affects the spirit of 100% revenue share will be treated as a violation.
*  15) Revenue sharing defined.
*     a) includes direct revenue and also intangible gains like brand, and organization.
*     b) No personal judgment should be involved in judging the distribution of revenue.It has to be pre-defined formula based.
*     c)100% of revenue should be shared before expenses and recievers should have control over what expenses to incur.
*     d)For the work done in any month by contributing group member, working on any project can be given revenue share from the work done by the group, for a maximum of 18 months after that month.
*     e)Revenue should be apportioned to the month in which work is done and not when received.
*  The group fulfilling the above conditions also has to be a wiki ecosystem further defined in www.wekosystem.org or read about Wekosystem at www.wikiocean.net

*  ******************************************************************************
*/  
package combinereport.fieldlist;


import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Map;
import java.util.Vector;

import combinereport.query.Resultset;

import utility.Input;
import file.SearchRecord;
import dbmanager.Column;
import dbmanager.DBManager;
import dbmanager.GetIdName;

public class Master_table implements Fieldlist
{
	DBManager dbSql;
	GetIdName gid;
	String CONDITION="Condition";
	String FIELDLIST="field";
	SearchRecord sr;
	String MASTERNAME="mastername";
	String buffer[];
	String fieldString = null;
	String Fieldobject="";
	String object;
	String reportName;
	String ALIES="alies";
	Vector<Object> FieldVector;
	String QUERY;
	String Split[]={};
	String Querybuffer[];
	/**
	 * set database object and find master id of Field
	 * @param db is database object
	 */
	public void setDbmanager(DBManager dbSql) 
	{
		this.dbSql=dbSql;
		gid = new GetIdName(dbSql);	
		MASTERNAME = gid.getId(MASTERNAME);
	}
	/**
	 *  return buffer
	 * @return buffer : String array
	 */ 
	public String [] getbuffer()
	{
		StringBuffer FinalResult = new StringBuffer();
		try 
		{
			for(int i=0;i<FieldVector.size();i++)
			{	
				try {
					Hashtable<Object, Object> tempfieldlist = new Hashtable<Object, Object>();
					tempfieldlist = (Hashtable<Object, Object>) FieldVector.get(i);
					if(tempfieldlist.containsKey(ALIES))
					{
						String name =gid.getItem(tempfieldlist.get(ALIES).toString());
						if(name.equals("no$"))
							name =(tempfieldlist.get(ALIES).toString());
						FinalResult.append(name +"\t");				
					}		
					else
					{	
						String name =gid.getItem(tempfieldlist.get(FIELDLIST).toString());
						if(name.equals("no$"))
							name =(tempfieldlist.get(FIELDLIST).toString());
						FinalResult.append(name+"\t");
					}
				} catch (Exception e) 
				{
					e.printStackTrace();
				}	
			}
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		Hashtable<Object, Object> resulthash =new Hashtable<Object, Object>();
		try 
		{
			ResultSet rs = dbSql.getSelect(QUERY);
			while(rs.next())
			{	
				String mastername=rs.getString("mid");
				if(resulthash.containsKey(mastername))
				{
					Vector<Object> propertyvector= (Vector<Object>) resulthash.get(mastername);
					Hashtable<Object, Object> propertyhash =new Hashtable<Object, Object>();					
					String key =  (rs.getString("pid"));
					String value =  (rs.getString("pv"));
					if(value.equals("0"))
						value = rs.getString("vt");
					else	
						value = gid.getItem(value);
					try {
						propertyhash.put(key, value);
					} catch (Exception e) {
						propertyhash.put(key, "null");
					}
					propertyvector.add(propertyhash);
				}
				else					
				{
					Vector<Object> propertyvector= new Vector<Object>();
					Hashtable<Object, Object> propertyhash =new Hashtable<Object, Object>();					
					String key =  (rs.getString("pid"));
					String value =  (rs.getString("pv"));
					if(value.equals("0"))
						value = rs.getString("vt");
					else	
						value = gid.getItem(value);
					propertyhash.put(key, value.toLowerCase());
					propertyvector.add(propertyhash);
					resulthash.put(mastername,propertyvector);
				}	
			}
		}
		catch (SQLException e2) 
		{	
			e2.printStackTrace();
		}
		
		FinalResult.append("\n");
		Enumeration<Object> enumforresulthash = resulthash.keys();
		while(enumforresulthash.hasMoreElements())
		{
			String mastername = enumforresulthash.nextElement().toString();

			Vector<Object> property = new Vector<Object>();
			property.addAll( (Collection<? extends Object>) resulthash.get(mastername));
			
			for(int i=1;i<Split.length;i++)
			{
				try {
					boolean flag=false;
					if(Split[i].equals(MASTERNAME))
						FinalResult.append(gid.getItem(mastername)+"\t");
					else
					{
						for(int j=0;j<property.size();j++)					
						{
							Hashtable<Object, Object> temphash= new Hashtable<Object, Object>();
							temphash.putAll((Map<? extends Object, ? extends Object>) property.get(j));
							if(temphash.containsKey(Split[i]))
							{
								FinalResult.append(temphash.get(Split[i]).toString()+"\t");
								flag = true;
								break;
							}
						}	
						if(!flag)
							FinalResult.append("null\t");
					}
				} catch (RuntimeException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}	
			}
			FinalResult.append("\n");
		}
			
		String temp = FinalResult.toString();
		buffer = temp.split("\n");

		return buffer;
	}
	/**
	 * set buffer
	 * @param buffer:String Array 
	 */
	public void setbuffer(String buffer[])
	{
		this.buffer = buffer;
	}
	/**
	 * set field Object 
	 * @param Object is condition object
	 */
	public void setFieldVector(Vector<Object> FieldVector)
	{
		this.FieldVector = FieldVector;
	}
	/**
	 * generate final buffer by finding all field  
	 * @return void
	 */
	public void getResult()
	{
		
	
		Hashtable<Object, Object> table = new Hashtable<Object, Object>();
		
		
		int count=1;
		Split = new String[FieldVector.size()+1];
		if(FieldVector.size()>1)
			QUERY = QUERY + " and (";
		for(int i=0;i<FieldVector.size();i++)
		{			
			Hashtable<Object, Object> tempfieldlist = new Hashtable<Object, Object>();
			tempfieldlist = (Hashtable<Object, Object>) FieldVector.get(i);
			if(tempfieldlist.containsKey(FIELDLIST))
			{
				Split[count] = tempfieldlist.get(FIELDLIST).toString();
				QUERY = QUERY + "p_2.pid=" + Split[count] + " or ";
				count++;
			}		
		}
		QUERY =  QUERY.substring(0,QUERY.length()-3);
		QUERY = QUERY + ")";
		
		}
	
	public static void main(String[] args) 
	{
		/*DBManager db =new DBManager();
		db.getConnect();
		Master_table mt =new Master_table();
		combinereport.condition.Master_table con = new combinereport.condition.Master_table();
		con.setDbmanager(db);
		//con.setObject("6260");
		//con.initializeData();
		
		
		Hashtable<Object, Object> table =new Hashtable<Object, Object>();
		Vector<Object> condition = new Vector<Object>();
		table.put(combinereport.condition.Condition.CONDITIONFIELD, "9");
		table.put(combinereport.condition.Condition.CONDITIONVALUE, "25");
		table.put("logicaloperator", "and");
		condition.add(table);		
		Hashtable<Object, Object> table1 =new Hashtable<Object, Object>();
		table1.put(combinereport.condition.Condition.CONDITIONFIELD, "7");
		table1.put(combinereport.condition.Condition.CONDITIONVALUE, "549");
		table1.put("logicaloperator", "and");
		condition.add(table1);
		con.setConditionMap(condition);		
		con.getResult(); 
		con.QUERY
	//	mt.setbuffer(con.getbuffer());
		//mt.setObject("6246");
		mt.setDbmanager(db);
		mt.getResult();
		String buffer2[] = mt.getbuffer();
		for(int i=0;i<buffer2.length;i++)
		{
			System.out.println(buffer2[i]);
		}
		//find retailer,emailid where mobileno +919922918607
		 //mt.getResult("|field,mastername,mobileno,Personcode,emailid|Condition,=,type,Employee,");
		//mt.getResult("|field,type|Condition,personcode,=,aac");
		//mt.getResult("|field,|Condition,type,=,user");
		//mt.getResult("|field,mastername|Condition,type,=,user");//for i card
		//mt.getResult("|field,");*/
	}

	public String getObject() 
	{
		return Fieldobject;
	}
	/**
	 * generate final buffer   <p> when process is add in report_master then addreport method is called.
	 * addreport method call getresult method <p>
	 */

	public void addReport()
	{
		getResult();
	}

	public void setReportName(String reportName) 
	{
		this.reportName = reportName;
	}
	/**
	 * generate final buffer   <p> when process is mod in report_master then updatereport method is called.
	 * updatereport method call getresult method <p>
	 */
	public void updateReport() 
	{
		getResult();
	}
	public String getQuery() 
	{
		return QUERY;
	}
	public void setQuery(String Query) 
	{
		this.QUERY = Query;	
	}
	
	public void setQueryCount(int count) {
		// TODO Auto-generated method stub
		
	}
	
	public void setQuerybuffer(String[] Querybuffer) 
	{
		this.Querybuffer = Querybuffer;
	}	
}

